package site.hanzhe.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import site.hanzhe.constant.CrowdConstant;
import site.hanzhe.entity.AdminEntity;
import site.hanzhe.exception.AdminDeleteException;
import site.hanzhe.security.AdminDetails;
import site.hanzhe.service.AdminService;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员管理的Controller
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    // 登录
    //@PostMapping("/do/login.html")
    public String doLogin(AdminEntity entity, HttpSession session) {
        // 登录成功session存储信息：loginAdmin
        entity = adminService.selectAdminByLoginAcct(entity);
        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, entity);
        // 设置session存活时间为10分钟
        session.setMaxInactiveInterval(CrowdConstant.SESSION_MAX_INTERVAL * 60);
        return "redirect:/admin/to/main/page.html";
    }

    // 退出
    //@GetMapping("/do/logout.html")
    public String doLogout(HttpSession session) {
        // 设置session失效
        session.invalidate();
        return "redirect:/admin/to/login/page.html";
    }

    // 查询所有管理员遍历显示到admin-page
    @GetMapping("/get/page.html")
    @PreAuthorize("hasAuthority('user:get')")
    public String getPageInfo(
            // 这里因为要设置默认值，所以就使用了RequestParam注解
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = CrowdConstant.PAGE_LIST_SIZE) Integer size,
            @RequestParam(value = "query", defaultValue = "") String query,
            Model model) {
        model.addAttribute("info", adminService.selectAdminByQuery(current, size, query));
        return "admin-page";
    }

    // 添加管理员用户
    @PostMapping("/insert.html")
    @PreAuthorize("hasAuthority('user:add')")
    public String insert(AdminEntity entity) {
        adminService.insertAdmin(entity);
        // 插入完成后跳转到列表页，保持显示最后一页让用户看到刚刚添加的效果
        return "redirect:/admin/get/page.html?current=" + Integer.MAX_VALUE;
    }

    // 跳转到修改页面
    @GetMapping("/to/edit/page.html")
    @PreAuthorize("hasAuthority('user:edit')")
    public String toEditPage(Integer id, Model model) {
        // 这里查询到最新的用户信息跳转到更新页面
        model.addAttribute("admin", adminService.selectAdminById(id));
        return "admin-edit";
    }

    // 更新管理员信息
    @PostMapping("/update.html")
    @PreAuthorize("hasAuthority('user:edit')")
    public String update(AdminEntity entity) {
        // 修改执行成功之后返回到列表页面，尽量让修改效果可以看到
        adminService.updateAdmin(entity);
        return "redirect:/admin/get/page.html?query=" + entity.getAccount();
    }

    // 移除单个管理员，这里需要注意的是query属性不一定会有值，所以把它放在最后
    @GetMapping("/delete/{id}/{current}/{query}.html")
    @PreAuthorize("hasAuthority('user:delete')")
    public String adminDelete(
            @PathVariable("id") Integer id,
            @PathVariable("current") Integer current,
            @PathVariable("query") String query,
            Authentication principal) {
        // 这里摒弃了之前session，通过Principal获取到当前登录人的信息
        AdminEntity entity = ((AdminDetails) principal.getPrincipal()).getEntity();
        // 对比ID 防止自己删除自己的惨案
        if (entity.getId().equals(id))
            throw new AdminDeleteException("自己不能删除自己");
        adminService.deleteAdminById(id);
        return "redirect:/admin/get/page.html?query=" + query + "&current=" + current;
    }

    @PostMapping("/deleteBatch.html")
    @PreAuthorize("hasAuthority('user:delete')")
    public String deleteAdminByIdList(Integer current, String query, String adminIds, Authentication principal) {
        // 获取当前登录人信息
        AdminEntity entity = ((AdminDetails) principal.getPrincipal()).getEntity();
        // 将选中的id转换为List集合，如果id中包含当前登录人则移除当前登录人，避免自己删除自己
        List<Integer> adminIdList = new ArrayList<>();
        for (String id : adminIds.split(",")) {
            Integer adminId = new Integer(id);
            if (!adminId.equals(entity.getId())) {
                adminIdList.add(adminId);
            }
        }
        // 执行批量删除
        if (!adminIdList.isEmpty()) {
            adminService.deleteBatchByIds(adminIdList);
        }
        return "redirect:/admin/get/page.html?query=" + query + "&current=" + current;
    }

}